<style rel="stylesheet/scss" lang="scss" scoped>
@import "../../../styles/prod.scss";
.mid {
  line-height: 140px;
}
</style>

<template>
  <div class="app-container calendar-list-container">
    <!-- 基本属性 -->
    <div class="pds-tip-green">
      <p>
        新增客户
        <el-radio-group v-model="detail.pdsCustomer.customerStatus" style="margin-left:20px" :disabled="detail.pdsCustomer.id?true:false">
          <el-radio :label="option.id" v-for="option in customerStatusOptions" :key="option.id">{{language=='en'?option.labelEnUs:option.labelZhCh}}</el-radio>
        </el-radio-group>
      </p>
    </div>
    <custom-card title="基本信息" class="mt-30">
      <template>
        <basic-form :basicInfo="basicForm_pre" :ruleForm="detail.pdsCustomer" ref="basicForm"></basic-form>
        <el-collapse>
          <el-collapse-item>
            <basic-form :basicInfo="basicForm_af" :ruleForm="detail.pdsCustomerBasicInfo" ref="basicForm_basic" v-if="detail.pdsCustomer.customerStatus==2"></basic-form>
            <basic-form :basicInfo="levelForm" :ruleForm="detail.pdsCustomerBasicInfo" ref="basicForm_rating"></basic-form>
          </el-collapse-item>
        </el-collapse>
        <custom-card title="联系人信息" class="mt-30">
          <template>
            <el-button type="primary" name="" class="mt-20" @click="addContact()">添加</el-button>
            <el-table class="" border fit highlight-current-row style="width: 100%" :data="detail.pdsCustomerContactsList">
              <el-table-column width="80px" align="center" label="序号" prop="" type="index"></el-table-column>
              <el-table-column align="center" label="姓名">
                <template slot-scope="scope">
                  <el-input class="filter-item" v-model="scope.row.contactName" placeholder="请输入内容" required></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="职位">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.contactPosition" placeholder="请选择">
                    <el-option v-for="option in contactPositionOptions" :key="option.id" :label="language=='en'?option.labelEnUs:option.labelZhCh" :value="option.id.toString()">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="电话">
                <template slot-scope="scope">
                  <el-input class="filter-item" v-model="scope.row.contactPhone" placeholder="请输入内容" required></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="邮箱">
                <template slot-scope="scope">
                  <el-input class="filter-item" v-model="scope.row.contactEmail" placeholder="请输入内容" required></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="100px">
                <template slot-scope="scope">
                  <el-button size="small" type="danger" @click="delContact(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </custom-card>
        <custom-card title="关联公司" class="mt-30">
          <template>
            <el-button type="primary" name="" class="mt-20" @click="addContact()">添加</el-button>
            <el-table class="" border fit highlight-current-row style="width: 100%" :data="detail.pdsCustomerContactsList">
              <el-table-column width="80px" align="center" label="序号" prop="" type="index"></el-table-column>
              <el-table-column align="center" label="关联公司">
                <template slot-scope="scope">
                  <!-- <el-input class="filter-item" v-model="scope.row.contactName" placeholder="请输入内容" required></el-input> -->
                  <el-select v-model="scope.row.addContact" placeholder="请选择">
                    <el-option v-for="option in contactPositionOptions" :key="option.id" :label="language=='en'?option.labelEnUs:option.labelZhch" :value="option.id.toString()">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="关联公司性质">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.addContact" placeholder="请选择">
                    <el-option v-for="option in contactPositionOptions" :key="option.id" :label="language=='en'?option.labelEnUs:option.labelZhch" :value="option.id.toString()">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </custom-card>
      </template>
    </custom-card>

    <custom-card title="合作条款" class="mt-30" v-if="detail.pdsCustomer.customerStatus==2">
      <template>
        <basic-form :basicInfo="conditionForm" :ruleForm="detail.pdsCustomerTerms" ref="basicForm_terms"></basic-form>
      </template>
    </custom-card>

    <custom-card title="信用检查" class="mt-30" v-if="detail.pdsCustomer.customerStatus==2">
      <template>
        <basic-form :basicInfo="conditionForm" :ruleForm="detail.pdsCustomerTerms" ref="basicForm_terms"></basic-form>
      </template>
    </custom-card>

    <custom-card title="业务信息" class="mt-30" v-if="detail.pdsCustomer.customerStatus==2">
      <template>
        <basic-form :basicInfo="businessForm" :ruleForm="detail.pdsCustomerBizInfo" ref="basicForm_biz"></basic-form>
        <custom-card title="主要产品信息" class="mt-30">
          <template>
            <el-button type="primary" name="" class="mt-20" @click="addProduct()">添加</el-button>
            <el-table class="" border fit highlight-current-row style="width: 100%" :data="detail.pdsCustomerProductsList">
              <el-table-column width="80px" align="center" label="序号" type="index"></el-table-column>
              <el-table-column align="center" label="型号">
                <template slot-scope="scope">
                  <el-input class="filter-item" v-model="scope.row.productModel" placeholder="请输入内容" required></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="主要规格">
                <template slot-scope="scope">
                  <el-input class="filter-item" v-model="scope.row.productSpec" placeholder="请输入内容" required></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="品牌">
                <template slot-scope="scope">
                  <el-input class="filter-item" v-model="scope.row.productBrand" placeholder="请输入内容" required></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="定位">
                <template slot-scope="scope">
                  <el-input class="filter-item" v-model="scope.row.productPositioning" placeholder="请输入内容" required></el-input>
                </template>
              </el-table-column>
              <el-table-column width="100px" align="center" label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="danger" @click="delProduct(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </custom-card>
      </template>
    </custom-card>
    <!-- <custom-card title="合作条款" class="mt-30" v-if="detail.pdsCustomer.customerStatus==2">
      <template>
        <basic-form :basicInfo="conditionForm" :ruleForm="detail.pdsCustomerTerms" ref="basicForm_terms"></basic-form>
      </template>
    </custom-card> -->
    <custom-card title="我方满足客户需求的能力" class="mt-30" v-if="detail.pdsCustomer.customerStatus==2">
      <template>
        <basic-form :basicInfo="abilityForm" :ruleForm="detail.pdsCustomerOurAbility" ref="basicForm_ability"></basic-form>
      </template>
    </custom-card>
    <custom-card title="深入了解客户" class="mt-30" v-if="detail.pdsCustomer.customerStatus==2">
      <template>
        <basic-form :basicInfo="moreForm" :ruleForm="detail.pdsCustomerDepthInfo" ref="basicForm_depth"></basic-form>
      </template>
    </custom-card>
    <!-- <custom-card title="客户评级" class="mt-30" v-if="detail.pdsCustomer.customerStatus==2">
      <template>
        <basic-form :basicInfo="levelForm" :ruleForm="detail.pdsCustomerBasicInfo" ref="basicForm_rating"></basic-form>
      </template>
    </custom-card> -->
    <custom-card title="财务报表" class="mt-30" v-if="detail.pdsCustomer.customerStatus==2">
      <upload-list v-model="detail.financialStatementsDocList"></upload-list>
    </custom-card>
    <custom-card title="近期媒体报道" class="mt-30" v-if="detail.pdsCustomer.customerStatus==2">
      <upload-list v-model="detail.mediaCoverageDocList"></upload-list>
    </custom-card>
    <div class="pds-btm mt-30">
      <div v-if="customerId && !detail.pdsCustomer.status&&detail.pdsCustomer.customerStatus!=1">
        已保存草稿
        <span class="tip">{{detail.pdsCustomer.updateTime | formatTime}}</span>
      </div>
      <div class="right">
        <el-button class="filter-item" type="warning" @click="submitForm('draft')" :loading="loading" v-if="!detail.pdsCustomer.status&&detail.pdsCustomer.customerStatus!=1">保存草稿</el-button>
        <el-button class="filter-item" type="primary" @click="submitForm('save')" :loading="loading">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import * as api from '@/api/sale/customer/index';
import BasicForm from '@/components/BasicForm/index';
import UploadList from '@/components/UploadList/index';
import mixins from './mixins/pub';
export default {
  name: 'user',
  components: {
    BasicForm,
    UploadList
  },
  mixins: [mixins],
  data() {
    return {};
  },
  created() {
    this.getDict();
  },
  activated() {
    this.refresh()
  },
  computed: {
    ...mapGetters(['elements', 'language'])
  },
  methods: {
    refresh() {
      if (this.$route.query.customerId) {
        this.customerId = this.$route.query.customerId;
        this.getPdsCustomerDetail();
        this.clearValidate()
      } else {
        this.detail = this.dataInit();
        this.clearValidate()
      }
    },
    clearValidate() {
      setTimeout(() => {
        for (const i in this.$refs) {
          this.$refs[i] && this.$refs[i].$refs.ruleForm.clearValidate();
        }
      })
    },
    // 添加联系人
    addContact() {
      let canAdd = true;
      const checkContactPerson = () => {
        this.detail.pdsCustomerContactsList.map(item => {
          if (!item.contactName) {
            this.$message.error('请填写联系人姓名！');
            canAdd = false;
          }
        });
      };
      checkContactPerson();
      if (canAdd) {
        this.detail.pdsCustomerContactsList.push({});
      }
    },
    // 删除联系人
    delContact(index) {
      this.detail.pdsCustomerContactsList.splice(index, 1);
    },
    // 添加产品
    addProduct() {
      let canAdd = true;
      const checkContactPerson = () => {
        this.detail.pdsCustomerProductsList.map(item => {
          if (!item.productModel) {
            this.$message.error('请填写客户产品型号！');
            canAdd = false;
          }
        });
      };
      checkContactPerson();
      if (canAdd) {
        this.detail.pdsCustomerProductsList.push({});
      }
    },
    // 删除产品
    delProduct(index) {
      this.detail.pdsCustomerProductsList.splice(index, 1);
    },
    async submitForm(type) {
      // 验证成功提交接口前数据整理
      const updateParams = JSON.parse(JSON.stringify(this.detail));

      const basicFormCheck = this.$refs.basicForm
        ? await this.$refs.basicForm.submitForm()
        : null;
      const checkSubmitFormList = [
        'basicForm_basic',
        'basicForm_biz',
        'basicForm_terms',
        'basicForm_ability',
        'basicForm_depth',
        'basicForm_rating'
      ];

      if (!basicFormCheck) {
        this.$message.error('请填写完整基本信息');
        return;
      }
      let checkSubmitFormListResult = true;
      if (type !== 'draft') {
        if (!this.detail.pdsCustomerContactsList.length) {
          this.$message.error('请至少填写一个联系人！');
          return;
        }
        if (this.detail.pdsCustomer.customerStatus === 2) {
          checkSubmitFormList.map(async item => {
            const formName = item;
            item = {};
            item.formChecked = await this.$refs[formName].submitForm();
            if (!item.formChecked) {
              checkSubmitFormListResult = false;
            }
          });
          if (!checkSubmitFormListResult) {
            this.$message.error('请填写完整必填信息');
            // return;
          }
          if (!this.detail.pdsCustomerProductsList.length) {
            this.$message.error('请至少填写一条产品信息！');
            return;
          }
        }
      }
      const setUpdateParams = () => {
        updateParams.pdsCustomerTerms.currencyDv = updateParams.pdsCustomerTerms.currencyDv.join(
          ','
        );
        updateParams.pdsCustomerBasicInfo.customerBusinessLicenseFile = {
          id: updateParams.pdsCustomerBasicInfo.customerBusinessLicenseFileId,
          fileName: updateParams.pdsCustomerBasicInfo.customerBusinessLicenseFileName,
          fileUrl: updateParams.pdsCustomerBasicInfo.customerBusinessLicenseFileUrl
        }
        updateParams.pdsCustomerBasicInfo.taxCardFile = {
          id: updateParams.pdsCustomerBasicInfo.taxCardFileId,
          fileName: updateParams.pdsCustomerBasicInfo.taxCardFileName,
          fileUrl: updateParams.pdsCustomerBasicInfo.taxCardFileUrl
        }
      };
      setUpdateParams();
      const updateToServer = () => {
        if (this.loading) return;
        this.loading = true;
        // 成功提交数据后的处理
        const submitCallback = res => {
          this.loading = false;
          if (res.code === 200) {
            this.$message.success((type === 'save' ? '提交' : '保存草稿') + '成功')
            //this.refreshCb(res);
            if (type === 'save') {
              this.$store.commit('ADD_LIST_REFRESH', this.$route.path.slice(0, this.$route.path.lastIndexOf('/')));
              this.$store.dispatch('delActiveViews');
            }
          } else {
            this.$message.error(res.message);
          }
        };
        if (type === 'draft') {
          api
            .savePdsCustomerToDraft(updateParams)
            .then(res => {
              submitCallback(res);
            })
            .catch(err => {
              console.log(err);
              this.loading = false;
            });
        }
        if (type !== 'draft') {
          // this.loading = false;
          // return;
          api
            .submitPdsCustomer(updateParams)
            .then(res => {
              submitCallback(res);
            })
            .catch(err => {
              console.log(err);
              this.loading = false;
            });
        }
      };
      updateToServer();
    }
  }
};
</script>
